package com.quanxiaoha.framework.biz.context.holder;


import com.alibaba.ttl.TransmittableThreadLocal;
import com.quanxiaoha.framework.common.constant.GlobalConstants;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: jingyan_liu
 * @CreateTime: 2025-07-14
 * @Description: 登录用户上下文
 * @Version: 1.0
 */


public class LoginUserContextHolder {
	
	// 当使用线程池等组件时，能够将任务提交线程中的值传递到执行任务的线程中
	private static final ThreadLocal<Map<String, Object>> LOGIN_USER_CONTEXT_THREAD_LOCAL
			= TransmittableThreadLocal.withInitial(HashMap::new);
	
	/**
	 * 获取用户 ID
	 */
	public static Long getUserId() {
		Object value = LOGIN_USER_CONTEXT_THREAD_LOCAL.get().get(GlobalConstants.USER_ID);
		if (Objects.isNull(value)) {
			return null;
		}
		return Long.valueOf(value.toString());
	}
	
	/**
	 * 设置用户 ID
	 */
	public static void setUserId(Object value) {
		LOGIN_USER_CONTEXT_THREAD_LOCAL.get().put(GlobalConstants.USER_ID, value);
	}
	
	/**
	 * 删除 TTL
	 */
	public static void remove() {
		LOGIN_USER_CONTEXT_THREAD_LOCAL.remove();
	}
	
}
